﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ebc.componentbinder
{
    /*
     * Original source: http://msdn.microsoft.com/en-us/library/ms228976.aspx
     * Code has been refactored and changed, though.
     */
    internal static class DelegateAnalysis
    {
        public static Type[] GetDelegateParameterTypes(Type d)
        {
            MethodInfo invoke = CheckForDelegateType(d);

            var typeParameters = new List<Type>();
            {
                typeParameters.AddRange(invoke.GetParameters()
                                              .Select(t => t.ParameterType));
            }
            return typeParameters.ToArray();
        }


        public static Type GetDelegateReturnType(Type d)
        {
            MethodInfo invoke = CheckForDelegateType(d);

            return invoke.ReturnType;
        }

        
        private static MethodInfo CheckForDelegateType(Type d)
        {
            if (d.BaseType != typeof(MulticastDelegate)) throw new ArgumentException("Not a delegate type!");

            MethodInfo invoke = d.GetMethod("Invoke");
            if (invoke == null) throw new ArgumentException("Not a delegate type!");
            return invoke;
        }
    }
}
